package com.glory.cqaospda.view

import android.Manifest
import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.nfc.tech.NfcA
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.provider.Settings
import android.text.InputType
import android.view.KeyEvent
import android.view.View
import android.widget.Toast
import com.glory.cqaospda.R
import com.glory.cqaospda.base.Constant
import com.glory.cqaospda.base.Constant.Companion.mfgList
import com.glory.cqaospda.base.MyApp
import com.glory.cqaospda.bean.*
import com.glory.cqaospda.utils.ByteArrayChange
import com.glory.cqaospda.viewmodel.LoginViewModel
import com.glory.mvvmnet.base.BaseActivity
import com.glory.mvvmnet.entity.ToastMessageBean
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_DownloadFragmentDialog
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_VersionEntity
import com.pda.platform.ui.ui_pdaplatform.utils_public.*
import kotlinx.android.synthetic.main.activity_login.*
import pub.devrel.easypermissions.AppSettingsDialog

import pub.devrel.easypermissions.EasyPermissions
import kotlin.system.exitProcess


class LoginActivity : BaseActivity<LoginViewModel>(), View.OnClickListener,
    EasyPermissions.PermissionCallbacks {
    var i = 0
    var mNfcAdapter: NfcAdapter? = null
    var mPendingIntent: PendingIntent? = null
    lateinit var mFilters: Array<IntentFilter>
    lateinit var mTechLists: Array<Array<String>>
    var mBackPressed = 0
    var mExitTime: Long = 0
    val PERMISSIONS_REQUEST_CODE = 10
    var handler: Handler = object : Handler() {
        @SuppressLint("HandlerLeak")
        override fun handleMessage(msg: Message) {
            when(msg.what) {
                0x10 -> {
                    var s: String = msg.obj as String
                    val intent = Intent()
                    intent.putExtra("type", "Error")
                    intent.putExtra("error", s)
                    val clazz = Class.forName("com.glory.cqaospda.view.SkipDialogActivity")
                    intent.setClass(this@LoginActivity, clazz)
                    startActivity(intent)
                }
            }
            super.handleMessage(msg)
        }
    }

    override fun layoutId(): Int {
        return R.layout.activity_login
    }


    override fun initView(savedInstanceState: Bundle?) {
        tvUser.text = "账号"
        tvPassword.text = "密码"
        lineWorkCard.visibility = View.GONE

        val instance = MyApp.instance
        instance!!.handler = handler

        btnLogin.setOnClickListener {
            if (Constant.isFastClick()) {
                if (etUser.text.toString().trim { it <= ' ' }.isEmpty()) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("请输入账号", false)
                    return@setOnClickListener
                }
                if (etPassword.text.toString().trim { it <= ' ' }.isEmpty()) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("请输入密码", false)
                    return@setOnClickListener
                }
//            startActivity(HomeActivity::class.java)
//            finish()
                viewModel.getLoginData("", etUser.text.toString(), etPassword.text.toString())
//                val callBack: FreeUI_EntityCallBack<BaseResponseBean<LogInfoBean>> = object :
//                    FreeUI_DialogEntityCallBack<BaseResponseBean<LogInfoBean>>(
//                        "请稍后...",
//                        object : TypeToken<BaseResponseBean<LogInfoBean?>?>() {}.type,
//                        supportFragmentManager,
//                        this
//                    ) {
//                    override fun onSuccess(response: Response<BaseResponseBean<LogInfoBean>>) {
//                        super.onSuccess(response)
//                        if (response.body().isSuccess(this@LoginActivity, true, supportFragmentManager)) {
//                            val mfgListBean = response.body().response.body
//
//                            val arrayList = mfgListBean!!.mfg_list as ArrayList<LogInfoBean.MfgListBean>
//                            mfgList.clear()
//                            mfgList.addAll(arrayList)
//                            Constant.UserName = mfgListBean.userid
//                            Constant.loginTime = FreeApi_DateUtils.getNowStringDate("HHmm")
//                            etUser.setText("")
//                            etPassword.setText("")
//                            viewModel.defUI.toastEvent.value = ToastMessageBean("登录成功", true)
//                            startActivity(HomeActivity::class.java)
//                            finish()
//                        }
//                    }
//
//                    override fun onError(response: Response<BaseResponseBean<LogInfoBean>>) {
//                        super.onError(response)
//
//                    }
//                }
//
//                val map = JsonObject()
//                map.addProperty("UserID", etUser.text.toString())
//                map.addProperty("UserPwd", etPassword.text.toString())
//                map.addProperty("CardID", "")
//                NetUtils.requestPostNet("EMS_UserLogIn","EMS_UserLogIn", this, map, callBack)
            }
        }
        rlParent.setOnClickListener(this)
        llParent.setOnClickListener(this)
        ivlogo.setOnClickListener(this)
        checkNFCFunction()
        mPendingIntent = PendingIntent.getActivity(
            this, 0, Intent(
                this,
                javaClass
            ).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0)
        // Setup an intent filter for all MIME based dispatches
        val ndef = IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED)
        try {
            ndef.addDataType("*/*")
        } catch (e: IntentFilter.MalformedMimeTypeException) {
            throw RuntimeException("fail", e)
        }
        mFilters = arrayOf(ndef)

        // 根据标签类型设置
        mTechLists = arrayOf(arrayOf(NfcA::class.java.name))
    }


    override fun initData() {
        requestPermission()
        ivPassword.setOnClickListener {
            val pos = etPassword.selectionStart
            if (etPassword.inputType !== InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD) {
                etPassword.inputType =
                    InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
                ivPassword.setImageDrawable(getResources().getDrawable(R.drawable.mi))
            } else {
                etPassword.inputType =
                    InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD

                ivPassword.setImageDrawable(getResources().getDrawable(R.drawable.ming))
            }
            etPassword.setSelection(pos)
        }

        viewModel.defUI.callObserve.observe(this) {
            if (!Constant.okgoError) {
                when (it.type) {
                    1 -> {
                        val mfgListBean = it.item as LogInfoBean

                        if (mfgListBean!!.mfg_list.size == 0 || mfgListBean.mfg_list == null) {
                            viewModel.defUI.toastEvent.value =
                                ToastMessageBean("当前登录人员无任何权限", false)
                            return@observe
                        }
                        val arrayList = mfgListBean.mfg_list as ArrayList<LogInfoBean.MfgListBean>
                        mfgList.clear()
                        mfgList.addAll(arrayList)
                        Constant.UserName = mfgListBean.userid
                        Constant.loginTime = FreeApi_DateUtils.getNowStringDate("HHmm")
                        etUser.setText("")
                        etPassword.setText("")
                        viewModel.defUI.toastEvent.value = ToastMessageBean("登录成功", true)
                        startActivity(HomeActivity::class.java)
                        finish()

                    }

                    2 -> {
                        val manager: PackageManager = this.packageManager
                        var info: PackageInfo? = null
                        try {
                            info = manager.getPackageInfo(this.packageName, 0)
                        } catch (e: PackageManager.NameNotFoundException) {
                            e.printStackTrace()
                        }
                        val version = info!!.versionName

                        val freeuiVersionentity = it.item as FreeUI_VersionEntity
                        freeuiVersionentity.currentVersion = version
                        FreeApi_SharePreferencesUtils.setSharePre(
                            "SystemSet",
                            "FILE_URL_DEBUG",
                            freeuiVersionentity.downUrl,
                            MyApp.app
                        )
                        val code =
                            FreeApi_Utils.compareVersion(version, freeuiVersionentity.version)
                        if (code == -1) {
                            val downloadFragmentDialog = FreeUI_DownloadFragmentDialog()
                            downloadFragmentDialog.setData(freeuiVersionentity)
                            downloadFragmentDialog.show(this.supportFragmentManager, "DOWNLOAD")
                        }
                    }
                }
            }else{
                Constant.okgoError = false
            }
        }
    }

    override fun onClick(view: View?) {
        i++
        if (i == 5) {
            i = 0
            startActivity(SystemSetActivity::class.java)
        }
    }

    override fun onResume() {
        super.onResume()

        if (Constant.isUpdate) {
            viewModel.initUser(this)
        }
        enableForegroundDispatch()
    }

    private fun enableForegroundDispatch() {
        // TODO 自动生成的方法存根
        if (mNfcAdapter != null) {
            mNfcAdapter!!.enableForegroundDispatch(
                this, mPendingIntent,
                mFilters, mTechLists
            )
        }
    }

    override fun onNewIntent(intent: Intent) {
        // TODO 自动生成的方法存根
        super.onNewIntent(intent)
        val intentActionStr = intent.action // 获取到本次启动的action
        if (NfcAdapter.ACTION_NDEF_DISCOVERED == intentActionStr || NfcAdapter.ACTION_TECH_DISCOVERED == intentActionStr || NfcAdapter.ACTION_TAG_DISCOVERED == intentActionStr) { // 未知类型
            // 在intent中读取Tag id
            val tag = intent.getParcelableExtra<Tag>(NfcAdapter.EXTRA_TAG)
            val bytesId = tag!!.id // 获取id数组
            val cardid = ByteArrayChange.ByteArrayToHexString(bytesId).toString()
            if (cardid == "") {
                viewModel.defUI.toastEvent.value = ToastMessageBean("未读取到信息", false)
            } else {
                viewModel.getLoginData(cardid, "", "")
            }
//            etWorkCard.setText(ByteArrayChange.ByteArrayToHexString(bytesId))
        }
    }

    private fun checkNFCFunction() {
        // TODO Auto-generated method stub
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this)
        // check the NFC adapter first
        if (mNfcAdapter == null) {

            FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "该设备未发现NFC功能", {

            }) {}.show(supportFragmentManager, "SUBMIT_DIALOG")

            return
        } else {
            if (!mNfcAdapter!!.isEnabled) {

                FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "NFC未开启,是否去开启？", {

                    val setnfc = Intent(
                        Settings.ACTION_NFC_SETTINGS
                    )
                    startActivity(setnfc)

                }) {}.show(supportFragmentManager, "SUBMIT_DIALOG")
                return
            }
        }
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(this, "再按一次返回键退出程序", Toast.LENGTH_SHORT).show()
                mExitTime = System.currentTimeMillis()
            } else {
                exitProcess(0)
            }

            return false
        }
        return super.onKeyUp(keyCode, event)
    }

    fun requestPermission() {
        //Manifest.permission.READ_PHONE_STATE 申请不到
        val perms: Array<String> = arrayOf(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE
        )
        //权限判断，第一次弹出系统的授权提示框
        //没有权限的话，先提示，点确定后弹出系统的授权提示框
        if (EasyPermissions.hasPermissions(this, *perms)) {
            //@AfterPermissionGranted 有权限直接执行 todo...
            //login();
        } else {
            EasyPermissions.requestPermissions(
                this, "程序运行需要权限",
                PERMISSIONS_REQUEST_CODE, *perms
            )
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>?) {
        TODO("Not yet implemented")
    }

    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>?) {
        viewModel.defUI.toastEvent.value = ToastMessageBean("用户授权失败", false)
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms!!)) {
            AppSettingsDialog.Builder(this).build().show()
        }
    }
}